import subprocess
import os
import signal
import time
import sys
import logging

log = logging.getLogger('ely.seleniumrctestlayer')

import seleniumrcconfig
sys.path.append(seleniumrcconfig.seleniumpythonpath)

from Testing import ZopeTestCase
from Products.PloneTestCase import PloneTestCase

from Products.PloneTestCase.layer import onsetup, onteardown

globals()['seleniumrcprocess'] = None

@onsetup
def startthings():
    print "Starting seleniumrc server"
    globals()['seleniumrcprocess'] = startSeleniumServer()
    ZopeTestCase.utils.startZServer(1)

startthings()

@onteardown
def stopthings():
    print "Stopping seleniumrc server"
    killAndWait(globals()['seleniumrcprocess'])

stopthings()

def startSeleniumServer():
    log = open('selenium.log','w')
    args = [seleniumrcconfig.javabinary,
            '-jar',
            seleniumrcconfig.seleniumserverjar,
            '-debug']
    process = subprocess.Popen(args, stdin=log, stdout=log, stderr=log)
    time.sleep(10) #XXXX YUK XXX urllib.urlretrieve('http://localhost:4444/selenium-server/driver?')[1].status
    return process

def killAndWait(process):
    os.kill(process.pid, signal.SIGTERM)
    # wait for any finishing up of this process to complete before
    # nailing the whole shebang
    process.wait()
